class PasswordReminderController < ApplicationController
  layout "login"

  def index
  end

  def remind
    user_form = params[:user]
    
    return if check_params(params[:user].nil?)
    
    login = user_form[:login].strip
    email = user_form[:email].strip

    if !email.empty?
      (user = User.find_by_email(email)) \
        ? on_data_correct(user) \
        : on_data_incorrect("There is no user with that email address.")
    elsif !login.empty?
      (user = User.find_by_login(login)) \
        ? on_data_correct(user) \
        : on_data_incorrect("That user name is not recognized.")
    else
      on_data_incorrect("Please enter your login or e-mail address")
    end
  end

  private
  def on_data_correct(user_)
    send_new_password(user_)
    set_flash_info(FlashInfo.new("Your new password has been sent to " + user_.email, FlashInfo::NOTICE))
    redirect_to :controller => "login"
  end

  def on_data_incorrect(message_)
    set_flash_info(FlashInfo.new(message_, FlashInfo::ERROR))
    redirect_to :action => :index
  end

  def send_new_password(user_)
    password = PasswordGenerator.generate
    user_.update_attribute("password", User.encrypt(password))
    PasswordReminder.deliver_remind(user_, password)
  end
end